package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.CookieManager;
import java.net.HttpCookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.User;
import cn.jhc.dao.DaoType;
import cn.jhc.dao.RoleRightDAO;
import cn.jhc.dao.TitleDAO;
import cn.jhc.dao.UserDao;
import cn.jhc.factory.DAOFactory;

/**
 * Servlet implementation   class showAddUserFromServlet
 */
@WebServlet("/login.htm")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String loginname = request.getParameter("username"); 
		String password = request.getParameter("password");
		UserDao userDao = (UserDao)DAOFactory.getDao(DaoType.USER);
		RoleRightDAO role = new RoleRightDAO();
		int id=1;
		if(userDao.Login(loginname, password)){
			id = role.findIdByName(loginname);
			User currentUser = userDao.findByLoginname(loginname);
			request.getSession().setAttribute("id", id);
			request.getSession().setAttribute("currentUser", currentUser);
			response.sendRedirect("list.htm");
		}
		else{
			PrintWriter out = response.getWriter();
			out.println("<script>window.alert('用户或密码错误！');</script>");
			response.sendRedirect("list.htm");
		}
	}
}
